<template>
  <div class="container">
    <div class="box">
      <div class="list">
        <div class="item" v-for="item in list" :key="item.id">{{ item.message }}</div>
      </div>
      <div class="empty-box"></div>
      <div class="footer">
        <input type="text" v-model="message" />
        <button @click="sendMessage">发送</button>
        <button @click="addMessageText">加文字</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { nextTick, ref } from 'vue'

const message = ref('')
const list = ref([])

list.value = [
  {
    id: 1,
    message: '你好啊'
  },
  {
    id: 2,
    message: '你好啊'
  },
  {
    id: 3,
    message: '你好啊'
  },
  {
    id: 4,
    message: '你好啊'
  },
  {
    id: 5,
    message: '你好啊'
  }
]

const sendMessage = () => {
  list.value.push({ id: list.value.length + 1, message: message.value })
  nextTick(() => {
    document.querySelector('.container').scrollTop = 0
  })
}
const addMessageText = () => {
  list.value[list.value.length - 1].message =
    list.value[list.value.length - 1].message + ' ' + message.value
}
</script>

<style lang="scss" scoped>
.container {
  height: 500px;
  width: 400px;
  overflow-y: scroll;
  overflow-x: hidden;
  display: flex;
  flex-direction: column-reverse;
  padding: 0 16px;
  border: 2px solid #eee;
  scroll-behavior: smooth;

  .box {
    width: 100%;
    flex: 1 1;
    align-self: center;
    display: flex;
    flex-direction: column;

    .list {
      display: flex;
      flex-direction: column;
    }

    .empty-box {
      flex-grow: 1;
    }

    .footer {
      position: sticky;
      width: 100%;
      bottom: 0;
      background: #fff;
    }
  }
}
</style>
